from .view import SearchView, SearchFavoriteView
from . import schema
import json, asyncio
from fastapi import APIRouter, Depends, Security, WebSocket, Request
from package.connector.sql_db import db
from package.fastapi import permission


router_search = APIRouter(prefix='/search', tags=['日志搜索'])
router_meta = {'module': '数据分析', 'sub_module': '日志搜索'}


# 直接搜索
@router_search.post('/', openapi_extra=router_meta, name='search',
                 summary='直接搜索')
def search(body: schema.SearchTimeline,
           user=Security(permission.security, scopes=['search:read'])):
    return SearchView.search_data(search=body.dict())


# 异步轮巡搜索任务
@router_search.post('/task', openapi_extra=router_meta, name='create_search_task',
                 summary='搜索任务创建')
def create_search_task(body: schema.SearchTimeline,
           user=Security(permission.security, scopes=['search:read'])):
    return SearchView.create_search_task(search=body.dict())


@router_search.get('/task', openapi_extra=router_meta, name='get_search_task',
                 summary='搜索任务结果')
def get_search_task(id: str,
                    user=Security(permission.security, scopes=['search:read'])):
    return SearchView.get_search_task(id)


@router_search.delete('/task', openapi_extra=router_meta, name='delete_search_task',
                 summary='搜索任务清除')
def delete_search_task(id: str,
                       user=Security(permission.security, scopes=['search:read'])):
    return SearchView.delete_search_task(id)


# websocket 方式搜索
@router_search.websocket('/websocket', name='search')
async def search(websocket: WebSocket, 
                 user=Security(permission.security_ws, scopes=['search:read'])):
    """主动推送"""
    await websocket.accept()
    search = await websocket.receive_json()
    await SearchView.search_websocket(search, websocket)
    await websocket.close()


@router_search.get('/history', response_model=schema.PageSearchHistory, openapi_extra=router_meta, name='history_list_get',
                 summary='搜索历史列表')
def history_list_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['history:read'])):
    return SearchView.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_search.get('/favorite', response_model=schema.PageSearchFavorite, openapi_extra=router_meta, name='favorite_list_get',
                 summary='收藏语句列表')
def favorite_list_get(q: str = None,
             page: int = 1,
             page_size: int = 10,
             order_by: str = 'created_at desc',
             session=Depends(db.get_session),
             user=Security(permission.security, scopes=['favorite:read'])):
    return SearchFavoriteView.get_page_items(session, q=q, page=page, page_size=page_size, order_by=order_by)


@router_search.post('/favorite', response_model=schema.SearchFavorite, openapi_extra=router_meta, name='favorite_post', summary='收藏语句创建')
def favorite_post(body: schema.SearchFavorite,
              session=Depends(db.get_session),
              user=Security(permission.security, scopes=['favorite:write'])):
    return SearchFavoriteView.create_model(session, body=body.dict())


@router_search.delete('/favorite', openapi_extra=router_meta, name='favorite_delete', summary='收藏语句删除')
def favorite_delete(body: schema.BatchId,
                session=Depends(db.get_session),
                user=Security(permission.security, scopes=['favorite:write'])):
    return {'count': SearchFavoriteView.delete_models(session, filter_=[SearchFavoriteView.id.in_(body.ids)])}
